﻿using AutoMapper;
using Inventory.API.Application.Command.WarehouseManagementCommand;
using Inventory.Domain;
using Inventory.Errorcode;
using Inventory.Errorcode.ErrorCode;
using Inventory.Infrastructure.Interfaces;
using MediatR;


namespace Inventory.API.Application.CommandHandler.WarehouseManagementCommandHandler
{
    public class AddWarehousingCommandHandler : IRequestHandler<AddWarehousingCommand, ApiResult>
    {
  

        private readonly IWarehousemanagementRepository _warehousemanagementRepository;

        private readonly ILogger<AddWarehousingCommandHandler> _logger;

        private readonly IMapper _mapper;

        public AddWarehousingCommandHandler(IWarehousemanagementRepository warehousemanagementRepository, ILogger<AddWarehousingCommandHandler> logger, IMapper mapper)
        {
            _warehousemanagementRepository = warehousemanagementRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult> Handle(AddWarehousingCommand request, CancellationToken cancellationToken)
        {

            try
            {
                var warehousing = _mapper.Map<Warehousemanagement>(request);
                var res = await _warehousemanagementRepository.InsertAsync(warehousing);
                if (res > 0)
                {
                    // 返回成功结果
                    return ApiResult.Success(StatusCodeEnum.Success);
                }
                else
                {
                    // 返回失败结果
                    return ApiResult.Fail("添加失败，请检查输入参数", StatusCodeEnum.InternalServerError);
                }


            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error when add warehousing");
                throw;
            }
        }
    }
}
